﻿namespace Brjnk.GpxExplorer.Data.ImportExport
{
    using System;
    using System.Collections.Generic;
    using System.Xml.Serialization;
    using Brjnk.GpxExplorer.Data.GPX;
    using Brjnk.GpxExplorer.Data.GPX.SerializationClasses;

    public class GpxReader : IDataReader
    {
        public DataReaderResult Load(System.IO.Stream stream)
        {
            //try
            //{
            gpxType data;
            var ex = Deserialize(stream, out data);
            if (ex != null) return new DataReaderResult(ex);

            IList<Waypoint> points = new List<Waypoint>();
            IList<Route> routes = new List<Route>();
            IList<Track> tracks = new List<Track>();

            foreach (var p in data.wpt) points.Add(new GpxWaypoint(p));
            foreach (var r in data.rte) routes.Add(new GpxRoute(r));
            foreach (var t in data.trk) tracks.Add(new GpxTrack(t));
            return new DataReaderResult(points, routes, tracks, string.Empty, null);
            //}
            //catch (Exception ex)
            //{
            //    return new DataReaderResult(ex);
            //}
        }

        private Exception Deserialize(System.IO.Stream stream, out gpxType data)
        {
            try
            {
                XmlSerializer s = new XmlSerializer(typeof(gpxType));
                data = s.Deserialize(stream) as gpxType;

                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Soubor se nepodařilo načíst deserializací do GPX verze 1.1. Bude proveden pokus o načtení do verze 1.0.\nException:" + ex.ToString());
            }

            //pokud je soubor ve verzi 1.0
            stream.Seek(0, System.IO.SeekOrigin.Begin);
            try
            {
                XmlSerializer s = new XmlSerializer(typeof(gpx1_0));
                data = (s.Deserialize(stream) as gpx1_0).WrappedData;
                return null;
            }
            catch (Exception ex)
            {
                //soubor se nepodařilo deserializovat
                data = null;
                return ex;
            }
        }

        public string FileDialogFilter
        {
            get
            {
                return "GPX|*.gpx|All files|*.*";
            }
        }
    }
}